<template>
  <div>
    <!--面包屑模块-->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="padding: 10px">
      <el-breadcrumb-item :to="{ path: '/manage/' + this.id }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图区域-->
    <el-card>
      <!--搜索区域-->
      <el-col :span="24">
        <el-col :span="16">
          <el-input placeholder="请输入用户ID查询" style="margin-bottom: 10px" v-model="queryInfo.query" clearable>
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" style="margin-left: 15px" @click="addUser">添加用户</el-button>
        </el-col>
      </el-col>
      <!-- 表格显示区 -->
      <el-table :data="userList" border style="width: 100%" ref="filterUser" stripe>
        <el-table-column prop="id" label="用户ID" width="150"></el-table-column>
        <el-table-column prop="password" label="密码" width="150">
          <template slot-scope="scope">
            <span>******</span>
          </template>
        </el-table-column>
        <el-table-column prop="role" label="角色" width="150">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.role === 0" type="danger">管理员</el-tag>
            <el-tag v-else-if="scope.row.role === 1" type="warning">教师</el-tag>
            <el-tag v-else-if="scope.row.role === 2" type="success">学生</el-tag>
            <el-tag v-else type="info">未知角色</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="修改角色" placement="top" :enterable="false">
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="editUserRole(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="重置密码" placement="top" :enterable="false">
              <el-button type="warning" size="mini" icon="el-icon-key" @click="resetPassword(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除用户" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.id)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页功能 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 15px">
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="addUserDialogVisible" width="50%" @close="addUserDialogClosed">
      <el-form :model="addUserForm" :rules="addUserFormRules" ref="addUserFormRef" label-width="100px">
        <el-form-item label="用户ID" prop="id">
          <el-input v-model="addUserForm.id"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="addUserForm.confirmPassword" type="password"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="addUserForm.role" placeholder="请选择角色">
            <el-option label="管理员" value="0"></el-option>
            <el-option label="教师" value="1"></el-option>
            <el-option label="学生" value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddUserForm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色对话框 -->
    <el-dialog title="修改用户角色" :visible.sync="editUserDialogVisible" width="50%" @close="editUserDialogClosed">
      <el-form :model="editUserForm" ref="editUserFormRef" label-width="100px">
        <el-form-item label="用户ID">
          <el-input v-model="editUserForm.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="editUserForm.role" placeholder="请选择角色">
            <el-option label="管理员" value="0"></el-option>
            <el-option label="教师" value="1"></el-option>
            <el-option label="学生" value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditUserForm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog title="重置用户密码" :visible.sync="resetPasswordDialogVisible" width="50%" @close="resetPasswordDialogClosed">
      <el-form :model="resetPasswordForm" :rules="resetPasswordFormRules" ref="resetPasswordFormRef" label-width="100px">
        <el-form-item label="用户ID">
          <el-input v-model="resetPasswordForm.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input v-model="resetPasswordForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="resetPasswordForm.confirmPassword" type="password"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetPasswordDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitResetPasswordForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'ManageUserRoles',
  data() {
    // 自定义验证规则：确认密码必须和密码一致
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.addUserForm.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    // 重置密码表单的确认密码验证
    const validateResetConfirmPassword = (rule, value, callback) => {
      if (value !== this.resetPasswordForm.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    return {
      id: sessionStorage.getItem('userID'),
      // 查询参数
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 10
      },
      // 用户列表数据
      userList: [],
      // 总数据条数
      total: 0,
      // 添加用户对话框可见性
      addUserDialogVisible: false,
      // 添加用户表单数据
      addUserForm: {
        id: '',
        password: '',
        confirmPassword: '',
        role: '2'
      },
      // 添加用户表单验证规则
      addUserFormRules: {
        id: [
          { required: true, message: '请输入用户ID', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 30, message: '长度在 6 到 30 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ],
        role: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ]
      },
      // 修改用户对话框可见性
      editUserDialogVisible: false,
      // 修改用户表单数据
      editUserForm: {
        id: '',
        role: ''
      },
      // 重置密码对话框可见性
      resetPasswordDialogVisible: false,
      // 重置密码表单数据
      resetPasswordForm: {
        id: '',
        password: '',
        confirmPassword: ''
      },
      // 重置密码表单验证规则
      resetPasswordFormRules: {
        password: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 30, message: '长度在 6 到 30 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validateResetConfirmPassword, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 获取用户列表
    getUserList() {
      this.$http.get('/user/all').then(response => {
        if (response.data.code === 200) {
          this.userList = response.data.data
          this.total = this.userList.length
          
          // 根据查询条件筛选
          if (this.queryInfo.query) {
            this.userList = this.userList.filter(user => 
              user.id.includes(this.queryInfo.query)
            )
            this.total = this.userList.length
          }
          
          // 分页处理
          const start = (this.queryInfo.pageNum - 1) * this.queryInfo.pageSize
          const end = start + this.queryInfo.pageSize
          this.userList = this.userList.slice(start, end)
        } else {
          this.$message.error('获取用户列表失败')
        }
      }).catch(error => {
        console.error('获取用户列表出错:', error)
        this.$message.error('获取用户列表失败')
      })
    },
    // 处理每页条数变化
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize
      this.getUserList()
    },
    // 处理页码变化
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage
      this.getUserList()
    },
    // 打开添加用户对话框
    addUser() {
      this.addUserDialogVisible = true
    },
    // 关闭添加用户对话框
    addUserDialogClosed() {
      this.$refs.addUserFormRef.resetFields()
    },
    // 提交添加用户表单
    submitAddUserForm() {
      this.$refs.addUserFormRef.validate(valid => {
        if (!valid) return
        
        // 创建要提交的用户对象（不包含确认密码）
        const user = {
          id: this.addUserForm.id,
          password: this.addUserForm.password,
          role: this.addUserForm.role
        }
        
        this.$http.post('/user/insert', user).then(response => {
          if (response.data.code === 200) {
            this.$message.success('添加用户成功')
            this.addUserDialogVisible = false
            this.getUserList()
          } else {
            this.$message.error('添加用户失败')
          }
        }).catch(error => {
          console.error('添加用户出错:', error)
          this.$message.error('添加用户失败')
        })
      })
    },
    // 打开修改用户角色对话框
    editUserRole(user) {
      this.editUserForm = JSON.parse(JSON.stringify(user))
      this.editUserDialogVisible = true
    },
    // 关闭修改用户角色对话框
    editUserDialogClosed() {
      this.$refs.editUserFormRef.resetFields()
    },
    // 提交修改用户角色表单
    submitEditUserForm() {
      this.$refs.editUserFormRef.validate(valid => {
        if (!valid) return
        
        this.$http.post('/user/update', this.editUserForm).then(response => {
          if (response.data.code === 200) {
            this.$message.success('修改用户角色成功')
            this.editUserDialogVisible = false
            this.getUserList()
          } else {
            this.$message.error('修改用户角色失败')
          }
        }).catch(error => {
          console.error('修改用户角色出错:', error)
          this.$message.error('修改用户角色失败')
        })
      })
    },
    // 打开重置密码对话框
    resetPassword(user) {
      this.resetPasswordForm.id = user.id
      this.resetPasswordForm.password = ''
      this.resetPasswordForm.confirmPassword = ''
      this.resetPasswordDialogVisible = true
    },
    // 关闭重置密码对话框
    resetPasswordDialogClosed() {
      this.$refs.resetPasswordFormRef.resetFields()
    },
    // 提交重置密码表单
    submitResetPasswordForm() {
      this.$refs.resetPasswordFormRef.validate(valid => {
        if (!valid) return
        
        const user = {
          id: this.resetPasswordForm.id,
          password: this.resetPasswordForm.password,
          role: this.userList.find(u => u.id === this.resetPasswordForm.id)?.role || '2'
        }
        
        this.$http.post('/user/update', user).then(response => {
          if (response.data.code === 200) {
            this.$message.success('重置密码成功')
            this.resetPasswordDialogVisible = false
          } else {
            this.$message.error('重置密码失败')
          }
        }).catch(error => {
          console.error('重置密码出错:', error)
          this.$message.error('重置密码失败')
        })
      })
    },
    // 删除用户
    deleteUser(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete(`/user/${id}`).then(response => {
          if (response.data.code === 200) {
            this.$message.success('删除用户成功')
            this.getUserList()
          } else {
            this.$message.error('删除用户失败')
          }
        }).catch(error => {
          console.error('删除用户出错:', error)
          this.$message.error('删除用户失败')
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  }
}
</script>

<style scoped lang="less">
.el-tag {
  margin-right: 5px;
}
</style>
